#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

moodle_db_password=$(get_attribute_value "moodle-db-password")
declare -r moodle_db_password

mysql -u root -e "CREATE USER 'moodleuser'@'localhost' IDENTIFIED BY '${moodle_db_password}'"
mysql -u root -e "GRANT ALL PRIVILEGES ON moodle.* TO 'moodleuser'@'localhost' IDENTIFIED BY '${moodle_db_password}'"
mysql -u root -e "FLUSH PRIVILEGES"

declare -a args=()
args+=( --lang=en \
  --dbuser=moodleuser \
  --dbpass="${moodle_db_password}" \
  --fullname="Moodle on Google Compute Engine" \
  --shortname="Moodle on GCE" \
  --summary="Welcome to your Moodle installation on GCE!" \
  --adminuser=admin \
  --adminpass="$(get_attribute_value "moodle-admin-password")" \
  --adminemail="$(get_attribute_value "moodle-admin-email")" \
  --non-interactive \
  --agree-license)

if has_external_ip; then
  args+=( --wwwroot=http://"$(get_external_ip)")
else
  args+=( --wwwroot=http://"$(get_internal_ip)")
fi

sudo -u www-data /usr/bin/php /var/www/html/admin/cli/install.php "${args[@]}"
